package com.example.homework.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework.db.models.Location
import com.example.homework.db.apis.RetrofitService
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class LocationViewModel : ViewModel() {
    private val _locationsStateFlow: MutableStateFlow<List<Location>> =
        MutableStateFlow<List<Location>>(listOf())
    val locationsFlow: Flow<List<Location>> = _locationsStateFlow.asStateFlow()

    init {
        loadData()
    }

    fun loadData(page: Int = 0) {
        viewModelScope.launch {
            _locationsStateFlow.value = RetrofitService.locationsApi.getAll(page).result
        }
    }

    fun getOne(id: Int): Location {
        val result: Deferred<Location> = viewModelScope.async {
            RetrofitService.locationsApi.getOne(id)
        }
        return runBlocking { result.await() }
    }
}